<?php
/**
 * TOP的数据请求模型
 * 
 * @version $Id: TopRequest.php 252 2012-03-30 08:49:25Z linsir123 $
 */
class TopRequest
{
	/**
	 * @var 阿里妈妈PID
	 */
	public $pid;
	
	/**
	 * @var 渠道号
	 * // 格式:英文和数字组成;长度不能大于12个字符
	 */
	public $outerCode;
	
	/**
	 * @var 是否开启缓存
	 */
	public $caching = true;
	
	/**
	 * @var 缓存的过期时间(3天)
	 */
	public $cacheLifeTime = 259200;
	
	/**
	 * @var 需要开启缓存的API列表
	 */
	public $cacheApis = array(
		//'usersGet',
		'itemcatsGet',
		//'itemGet',
		//'taobaokeItemsConvert',
		//'taobaokeShopsConvert',
		//'itemsSearch',
		//'taobaokeItemsGet',
	);
	
	/**
	 * 构造函数
	 */
	public function __construct()
	{
		$this->outerCode = 'e35go';
		$this->pid = App::O('taobaoke.pid');
		App::V('taobao');
	}
	
	/**
	 * 设置查询对象属性
	 */
	private function _setRequest(& $req, $methods, $params)
	{
		foreach ($methods as $f => $method) {
			if (isset($params[$f])) 
				call_user_func_array(array($req, $method), array($params[$f]));
		}
	}
	
	/**
	 * 调用API
	 */
	private function _callTopApi($req, $format = 'json')
	{
		$sender = M::topSender();
		return $sender->execute($req, $format);
	}
	
	/**
	 * 根据查询条件构造唯一的key
	 */
	private function _getCacheKey($params)
	{
		$key = serialize($params);
		return md5($key);
	}
	
	/**
	 * 缓存目录
	 */
	private function _getCacheFile($api, $key)
	{
		$dir = CACHE_DIR.'taobao/'.$api.'/'.$key[0].'/'.$key[1].'/';
		$file = $dir.$key.'.php';
		
		///
		lpDir::make($dir);
		return $file;
	}
	
	/**
	 * 检测缓存
	 */
	private function _getCacheState($api)
	{
		if ( ! $this->caching) 
			return false;
			
		///
		if ( ! in_array($api, $this->cacheApis)) 
			return false;
			
		return true;
	}
	
	/**
	 * 将查询结果进行缓存
	 */
	private function _saveCache($api, $key, $data)
	{
		if ($this->_getCacheState($api)) {
			$file = $this->_getCacheFile($api, $key);
			$content = "<?php \r\n return ".var_export($data, true).';';
			file_put_contents($file, $content);
		}
	}
	
	/**
	 * 取得查询缓存
	 * // 缓存时间设置有为一天
	 */
	private function _getCache($api, $key)
	{
		if ($this->_getCacheState($api)) {
			$file = $this->_getCacheFile($api, $key);
			if (file_exists($file)) {
				$time = filemtime($file);
				if (time() - intval($time) < $this->cacheLifeTime) 
					return require($file);
			}
		}
		
		return false;
	}
	
	/**
	 * 将数据打散开以供取某个商品时可以使用
	 */
	private function _saveItems($list)
	{
		return false; // 暂停
		
		if ( ! $this->caching) 
			return false;
			
		///
		$base = CACHE_DIR.'taobao/_items/';
		foreach ($list as $v) {
			$iid = strval($v['num_iid']);
			$tmp = md5($iid);
			$dir = $base.$tmp[0].'/'.$tmp[1].'/';
			lpDir::make($dir);
			
			///
			$file = $dir.$iid.'.php';
			$content = "<?php \r\n return ".var_export($v, true).';';
			file_put_contents($file, $content);
		}
	}
	
	
	///   以上方法为内部私有方法   ///
	
	
	/**
	 * 配置缓存状态
	 */
	public function setCaching($on = false)
	{
		$this->caching = $on;
	}
	
	/**
	 * 获取交易报告
	 */
	public function reportGet($params)
	{
		$params['fields'] = "app_key,outer_code,trade_id,pay_time,pay_price,num_iid,item_title,item_num,category_id,category_name,shop_title,commission_rate,commission,iid,seller_nick";
		$methods = array(
			'fields' => 'setFields', 			// 字段列表
			'date' => 'setDate', 				// 某一个日期
			'p' => 'setPageNo', 				// 分页
			'show' => 'setPageSize', 			// 每页个数
		);
		
		///
		$req = new TaobaokeReportGetRequest();
		$this->_setRequest($req, $methods, $params);
		
		///
		$data = $this->_callTopApi($req);
		return $data;
	}
	
	/**
	 * 获取卖家信息
	 * // 用户昵称，多个以半角逗号(,)分隔，最多40个
	 */
	public function usersGet($nicks)
	{
		/* 验证必填数据 */
		if (empty($nicks)) 
			return array();
			
		///
		$api = 'usersGet';
		
		///
		$key = $this->_getCacheKey($nicks);
		$data = $this->_getCache($api, $key);
		if ( ! $data) {
			///
			$req = new UsersGetRequest();
			$req->setFields('user_id,nick,seller_credit,location,consumer_protection,type');
			$req->setNicks($nicks);
			
			///
			$data = array();
			$tmp = $this->_callTopApi($req);
			if (isset($tmp['users'])) {
				$data = $tmp['users']['user'];
				$this->_saveCache($api, $key, $data);
			}
		}
		
		return $data;
	}
	
	/**
	 * 取得分类信息
	 */
	public function itemcatsGet($cids = "", $parentCid = 0)
	{
		/* 验证必填数据 */
		if (empty($cids) && empty($parentCid)) 
			return array();
			
		///
		$api = 'itemcatsGet';
		
		///
		$key = $this->_getCacheKey(array($cids, $parentCid));
		$data = $this->_getCache($api, $key);
		if ( ! $data) {
			$req = new ItemcatsGetRequest();
			$req->setFields("cid,parent_cid,name,is_parent");
			if ($cids) 
				$req->setCids($cids);
			if ($parentCid) 
				$req->setParentCid($parentCid);
			
			///
			$data = array();
			$tmp = $this->_callTopApi($req);
			if (isset($tmp['item_cats'])) {
				App::V('pinyin');
				foreach ($tmp['item_cats']['item_cat'] as $v) 
					$data[] = array(
						'id' => $v['cid'],
						'pid' => $v['parent_cid'],
						'title' => $v['name'],
						'pinyin' => string2pinyin($v['name']),
					);
					
				$this->_saveCache($api, $key, $data);
			}
		}
		
		return $data;
	}
	
	/**
	 * 获取商品信息
	 * // 由于数据包含富文本，所以采用xml
	 */
	public function itemGet($iid)
	{
		/* 验证必填数据 */
		if (empty($iid)) 
			return array();
			
		///
		$api = 'itemGet';
		
		///
		$key = $this->_getCacheKey($iid);
		$data = $this->_getCache($api, $key);
		if ( ! $data) {
			$req = new ItemGetRequest();
			$req->setFields("detail_url,num_iid,props_name,title,nick,type,cid,seller_cids,props,input_pids,input_str,desc,pic_url,num,valid_thru,list_time,delist_time,stuff_status,location,price,post_fee,express_fee,ems_fee,has_discount,freight_payer,has_invoice,has_warranty,has_showcase,modified,increment,approve_status,postage_id,product_id,auction_point,property_alias,item_img,prop_img,sku,video,outer_id,is_virtual");
			$req->setNumIid($iid);
			
			///
			$tmp = $this->_callTopApi($req, 'xml');
			if (isset($tmp['item'])) {
				$data = $tmp['item'];
				$this->_saveCache($api, $key, $data);
			}
		}
			
		return $data;
	}
	
	/**
	 * 获取店铺信息
	 * // 由于数据包含富文本，所以采用xml
	 */
	public function shopGet($nick)
	{
		/* 验证必填数据 */
		if (empty($nick)) 
			return array();
			
		///
		$req = new ShopGetRequest();
		$req->setFields('sid,cid,nick,title,desc,pic_path,created,shop_score');
		$req->setNick($nick);
		
		///
		$tmp = $this->_callTopApi($req, 'xml');
		if (isset($tmp['shop'])) 
			return $tmp['shop'];
			
		return array();
	}
	
	/**
	 * 根据商品ID列表取得转换的列表
	 * // 另外将数据打散
	 */
	public function taobaokeItemsConvert($iids)
	{
		/* 验证必填数据 */
		if (empty($iids)) 
			return array();
			
		///
		$api = 'taobaokeItemsConvert';
		
		///
		$key = $this->_getCacheKey($iids);
		$data = $this->_getCache($api, $key);
		if ( ! $data) {
			$req = new TaobaokeItemsConvertRequest();
			$req->setOuterCode($this->outerCode); // 渠道号
			$req->setPid($this->pid); // 设置PID
			$req->setNumIids($iids);
			$req->setFields('num_iid,title,nick,pic_url,price,click_url,commission,commission_rate,commission_num,commission_volume,shop_click_url,seller_credit_score,item_location,volume');
			
			///
			$data = array();
			$tmp = $this->_callTopApi($req);
			if (isset($tmp['taobaoke_items'])) {
				$data = $tmp['taobaoke_items']['taobaoke_item'];
				$this->_saveCache($api, $key, $data);
				$this->_saveItems($data);
			}
		}
		
		return $data;
	}
	
	/**
	 * 根据商店ID列表取得转换的列表
	 */
	public function taobaokeShopsConvert($sids)
	{
		$api = 'taobaokeShopsConvert';
		
		///
		$key = $this->_getCacheKey($sids);
		$data = $this->_getCache($api, $key);
		if ( ! $data) {
			$req = new TaobaokeShopsConvertRequest();
			$req->setOuterCode($this->outerCode); // 渠道号
			$req->setPid($this->pid); // 设置PID
			$req->setSids($sids);
			$req->setFields('user_id,shop_title,click_url,commission_rate');
			
			///
			$data = array();
			$tmp = $this->_callTopApi($req);
			if (isset($tmp['taobaoke_shops'])) {
				$data = $tmp['taobaoke_shops']['taobaoke_shop'];
				$this->_saveCache($api, $key, $data);
			}
		}
		
		return $data;
	}
	
	/**
	 * 商品搜索
	 */
	public function itemsSearch($params = array())
	{
		$api = 'itemsSearch';
		
		///
		//$params['fields'] = "iid,num_iid,title,pic_url,price,volume";
		$params['fields'] = "iid";
		$methods = array(
			'fields' => 'setFields', 			// 字段列表
			'nicks' => 'setNicks', 				// 商家呢称
			'p' => 'setPageNo', 				// 分页
			'cid' => 'setCid', 					// 分类
			'show' => 'setPageSize', 			// 每页个数
			'keyword' => 'setQ', 				// 查询关键字
			'sort' => 'setOrderBy', 			// 排序
			'start_price' => 'setStartPrice',	// 价格开始
			'end_price' => 'setEndPrice', 		// 价格结束
		);
		
		///
		$key = $this->_getCacheKey($params);
		$data = $this->_getCache($api, $key);
		if ( ! $data) {
			$req = new ItemsSearchRequest();
			$this->_setRequest($req, $methods, $params);
			
			///
			$tmp = $this->_callTopApi($req);
			if (isset($tmp['item_search']['items'])) {
				$total = $tmp['total_results'];
				$totalPage = ceil($total/$params['show']);
				$data = array(
					$tmp['item_search']['items']['item'], 
					$totalPage,
					$total,
					$tmp['item_search']['item_categories']['item_category'], 
				);
				
				$this->_saveCache($api, $key, $data);
			}
		}
		
		return $data;
	}
	
	/**
	 * 获取推广链接
	 * // 另外将数据打散
	 */
	public function taobaokeItemsGet($params = array())
	{
		$api = 'taobaokeItemsGet';
		
		///
		$params['pid'] = $this->pid;
		$params['outerCode'] = $this->outerCode;
		$params['fields'] = "num_iid,title,nick,pic_url,price,click_url,commission,commission_rate,commission_num,commission_volume,shop_click_url,seller_credit_score,item_location,volume";
		$methods = array(
			'pid' => 'setPid', 					// PID
			'outerCode' => 'setOuterCode', 		// 渠道号
			'fields' => 'setFields', 			// 字段列表
			'p' => 'setPageNo', 				// 分页
			'cid' => 'setCid', 					// 分类
			'sort' => 'setSort', 				// 排序
			'show' => 'setPageSize', 			// 每页个数
			'keyword' => 'setKeyword', 			// 查询关键字
			'start_price' => 'setStartPrice',	// 价格开始
			'end_price' => 'setEndPrice', 		// 价格结束
			'mallItem' => 'setMallItem', 		// 是否商城商品
		);
		
		///
		$key = $this->_getCacheKey($params);
		$data = $this->_getCache($api, $key);
		if ( ! $data) {
			$req = new TaobaokeItemsGetRequest();
			$this->_setRequest($req, $methods, $params);
			
			///
			$tmp = $this->_callTopApi($req);
			if (isset($tmp['taobaoke_items'])) {
				$total = $tmp['total_results'];
				$totalPage = ceil($total/$params['show']);
				$data = array(
					$tmp['taobaoke_items']['taobaoke_item'], 
					$totalPage,
					$total
				);
				
				$this->_saveCache($api, $key, $data);
				$this->_saveItems($tmp['taobaoke_items']['taobaoke_item']);
			}
		}
		
		return $data;
	}
}
